package com.wuye.web;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.LinkedList;

/**
 * Created by xieyp on 2015/8/24.
 */
public class Http {

    private Log log = LogFactory.getLog(this.getClass());
    public Http(String url) {
        if (url.startsWith("http://")) {
            this.url = url;
        } else {
            this.url = System.getProperty("api.host.prefix") + "/api/" + url;
        }
    }

    protected String url;
    protected LinkedList<NameValuePair> nvp = new LinkedList<>();

    public Http param(String n, String v) {
        nvp.add(new BasicNameValuePair(n, v));
        return this;
    }

    public Http param(String n, Object v) {
        nvp.add(new BasicNameValuePair(n, v.toString()));
        return this;
    }

    public JSONObject post() throws IOException {
        String html = _post();
        try {
            json = JSONObject.fromObject(html);
            if (json.containsKey("code")) code = json.getInt("code");
            return json;
        } catch (Exception e) {
            log.error("转换成JSONObject出错:\n\n\t" + url + "\n\t" + html);
            e.printStackTrace();
            throw e;
        }
    }

    private String _post() throws IOException {
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(nvp, "utf-8"));
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        post.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        HttpResponse response = client.execute(post);
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                return IOUtil.toString(response.getEntity());
            }
            log.error("获取数据出错:" + url);
            return null;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    public JSONObject postOk() throws IOException {
        json = JSONObject.fromObject(_post());
        if (json.containsKey("code")) code = json.getInt("code");
        if (isOk()) return json;
        return null;
    }

    public JSONObject json;
    public int code = -1;

    public boolean isOk() {
        return code == 0;
    }

    public JSONObject getJSONObject() throws IOException {
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        String apiUrl;
        if (url.startsWith("http://")) {
            apiUrl = url;
        } else {
            apiUrl = System.getProperty("api.host.prefix") + "/api/" + url;
        }
        HttpGet post = new HttpGet(apiUrl);
        HttpResponse response = client.execute(post);
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                json = JSONObject.fromObject(IOUtil.toString(response.getEntity()));
                return json;
            }
            log.error("获取数据出错:" + apiUrl);
            return null;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
}
